import { login, logout, getUserInfo, getUserResource } from '@/api/user'
import contextUtils from '@/libs/contextUtils'

export default {
  state: {
    userName: '',
    userId: '',
    account: '',
    resource: [],
    avatorImgPath: '',
    token: contextUtils.getToken(),
    access: ''
  },
  mutations: {
    setAvator (state, avatorPath) {
      state.avatorImgPath = avatorPath
    },
    setUserId (state, id) {
      state.userId = id
    },
    setAccount (state, account) {
      state.account = account
    },
    setUserName (state, name) {
      state.userName = name
    },
    setResource (state, resource) {
      state.resource = resource
    },
    setAccess (state, access) {
      state.access = access
    },
    setToken (state, token) {
      state.token = token
      contextUtils.setToken(token)
    }
  },
  actions: {
    // 登录
    handleLogin ({ commit }, {userName, password}) {
      userName = userName.trim()
      return new Promise((resolve, reject) => {
        login({
          userName,
          password
        }).then(res => {
          const data = res.data
          commit('setToken', data.token)
          resolve()
        }).catch(err => {
          reject(err)
        })
      })
    },
    // 退出登录
    handleLogOut ({ state, commit }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('setToken', '')
          commit('setAccess', [])
          resolve()
        }).catch(err => {
          reject(err)
        })
        // 如果你的退出登录无需请求接口，则可以直接使用下面三行代码而无需使用logout调用接口
        // commit('setToken', '')
        // commit('setAccess', [])
        // resolve()
      })
    },
    // 获取用户相关信息 account
    getUserInfo ({ state, commit }) {
      return new Promise((resolve, reject) => {
        if (!state.userId || state.userId === '') {
          getUserInfo().then(res => {
            const data = res.data
            // console.log(res, data)
            commit('setAvator', data.avator)
            commit('setUserName', data.userName)
            commit('setUserId', data.userId)
            commit('setAccount', data.account)
            return Promise.resolve(data)
          }, err => {
            reject(err)
          }).then(userInfo => {
            getUserResource().then(Response => {
              const {data} = Response
              commit('setResource', data)
              // console.log(data)
              resolve({userinfo: userInfo, resource: data})
            })
          }, err => {
            reject(err)
          })
        } else {
          resolve({userId: state.userId, userName: state.userName})
        }
      })
    }
  }
}
